from urllib.parse import urlencode
from urllib.request import Request, urlopen
import json
import logging as log

from info_config import platform_username
from info_config import platform_password
from info_config import db_platform_url


def message_format(body):
    # log.info(str(body))
    try:
        # message = bytes.decode(body)
        message = str(body)
        # message1 = json.loads(message)
        message_eval = eval(message)
        for key, value in message_eval.items():
            if isinstance(value, bytes):
                message_eval.update({key: str(value, encoding="utf-8")})
        return message_eval
    except Exception as e:
        log.exception(str(e))
        return


def get_token(username, password):
    message = {
        'eauth': "pam",
        "username": username,
        "password": password
    }
    auth_url = "/auth/token/user_login"
    request_url = "{db_platform_url}{auth_url}".format(db_platform_url=db_platform_url,
                                                       auth_url=auth_url)
    request = Request(request_url, urlencode(message).encode())
    body = urlopen(request).read().decode()
    token_info = message_format(body)
    token = token_info.get("token")
    log.debug(token)
    return "bearer " + token


def info_interactive_with_dbpt(suffix_url, args_send, method="POST"):
    token_get = get_token(username=platform_username, password=platform_password)
    args_send_format = json.dumps(args_send)
    base_url = db_platform_url
    request_url = "{}{}".format(base_url, suffix_url)
    req = Request(url=request_url,
                  data=bytes(
                      args_send_format.encode("utf-8")),
                  method=method)

    log.debug(request_url)
    req.add_header("Content-type", "application/json; charset=UTF-8")
    req.add_header("Authorization", token_get)
    with urlopen(req) as resp:
        response_data = json.loads(resp.read().decode("utf-8"))
        log.debug(response_data)
    return response_data
